//
//  NetWorkTool.swift
//  DHSWallet
//
//  Created by zhengyi on 2017/8/21.
//  Copyright © 2017年 zhengyi. All rights reserved.
//

import UIKit
import Alamofire
import SystemConfiguration
import SVProgressHUD

let timeoutIntervalForRequest: Int = 120

enum NetType: CustomStringConvertible {
    case WLWAN
    case WiFi
    
    var description : String {
        switch self {
        case .WLWAN: return "无线广域网"
        case .WiFi: return "WiFi"
        }
    }
}

enum NewStatus:CustomStringConvertible  {
    case OffLine
    case OnLine
    case Unknow
    
    var description: String {
        switch self {
        case .OffLine: return "离线"
        case .OnLine: return "在线"
        case .Unknow: return "未知"
        }
    }
}



class NetWorkTool: NSObject {
    
    class func requestData(_ requestType: HTTPMethod, URLString: String, parameters: [String : Any]?, showIndicator: Bool, success: @escaping (_ response : Any) -> () , failture: @escaping(_ error: Error) -> ()) {
        
        var requestParameters = parameters
        if parameters != nil {
            let jsonParameters =  Tools.getJSONStringFromDictionary(dictionary:parameters! as NSDictionary)
            requestParameters = ["data":jsonParameters]
        }
        
        let sessionManager = Alamofire.SessionManager.default
        sessionManager.session.configuration.timeoutIntervalForRequest = TimeInterval(timeoutIntervalForRequest)
        
        Tools.DLog(message:"url \(URLString), type \(requestType)")
        Tools.DLog(message:"params \(String(describing: parameters))")
        
        if parameters != nil {
            sessionManager.request(URLString, method: requestType, parameters: requestParameters).validate().responseJSON { (response) in
                
                Tools.DLog(message:"all response info \(response)")

                switch response.result {
                case .success(let value):
                    success(value)
                    
                case .failure(let error):
                    Tools.DLog(message:"error \(error.localizedDescription)")
                    failture(error)
                    if showIndicator {
                        SVProgressHUD.showError(withStatus: "无法连接到网络，请稍后重试")
                    }
                }
            }
        } else {
            sessionManager.request(URLString, method: requestType).validate().responseJSON { (response) in
                
                Tools.DLog(message:"all response info \(response)")
                
                switch response.result {
                case .success(let value):
                    success(value)
                    
                case .failure(let error):
                    
                    Tools.DLog(message:"error \(error.localizedDescription)")
                    failture(error)
                    if showIndicator {
                        SVProgressHUD.showError(withStatus: "无法连接到网络，请稍后重试")
                    }
                }
            }
        }
    }
    
    //关于文件上传的方法(支持多或者单上传)
    class func uploadPictures(url: String, parameter :[String:Any]?, image: UIImage, imageKey: String,success : @escaping (_ response : [String : AnyObject])->(), fail : @escaping (_ error : Error)->()){
        let requestHead = ["content-type":"multipart/form-data"]
        Alamofire.upload(
            multipartFormData: { multipartFormData in
                if parameter != nil {
                    /*
                    for (key,value) in parameter!{
                        let valuedata = (value as! String).data(using: String.Encoding.utf8)
                        multipartFormData.append(valuedata!, withName:key)
                        Tools.DLog(message: multipartFormData)
                    }*/
                    
                    let token = UserDefaults.standard.value(forKey: "token")
                    let params = ["token" : token]
                    let jsonParameters =  Tools.getJSONStringFromDictionary(dictionary:params as NSDictionary)
                    let requestParameters = ["data":jsonParameters]
                    
                    multipartFormData.append(jsonParameters.data(using: String.Encoding.utf8)!, withName: "data")
                    Tools.DLog(message: url)
                    Tools.DLog(message: multipartFormData)

                }
                let imageName = Tools.getCurrentTime() + ".jpg"
                multipartFormData.append(UIImageJPEGRepresentation(image, 0.1)!, withName: "photo", fileName: imageName, mimeType: "image/jpeg")
        },
            to: url,
            headers: requestHead,
            encodingCompletion: { result in
                switch result {
                    
                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        if let value = response.result.value as? [String: AnyObject]{
                            success(value)
                        }
                    }
                    
                case .failure(let error):
                    fail(error)
                }
        }
        )
    }
}
